package com.mywork.mvpkodeingithub.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.mywork.mvpkodeingithub.R
import com.orhanobut.logger.Logger
import com.squareup.picasso.Picasso

class UsersAdapter : RecyclerView.Adapter<UsersAdapter.ViewHolder>() {
    private val users = ArrayList<UserWithSource>()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.user_view, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val userWithSource = users[position]
        holder.tv_name.text = userWithSource.user.login
        holder.tv_source.text = userWithSource.getSource()

        Picasso.with(holder.iv_avatar.context).load(userWithSource.user.avatar_url)
            .centerCrop()
            .fit()
            .into(holder.iv_avatar)

        holder.root.setOnClickListener {
            /*ReposUserActivity.selectedUser = userWithSource.getUser();
                startActivity(new Intent(UsersActivity.this, ReposUserActivity.class));*/
            Logger.d("id:${users[position].user.id},login:${users[position].user.login}")
        }
    }

    override fun getItemCount(): Int {
        return users.size
    }

    inner class ViewHolder(internal var root: View) : RecyclerView.ViewHolder(root) {
        internal var iv_avatar: ImageView
        internal var tv_name: TextView
        internal var tv_source: TextView

        init {
            iv_avatar = root.findViewById<View>(R.id.iv_avatar) as ImageView
            tv_name = root.findViewById<View>(R.id.tv_name) as TextView
            tv_source = root.findViewById<View>(R.id.tv_source) as TextView
        }
    }

    fun addData(data: List<UserWithSource>) {
        users.addAll(data)
        notifyDataSetChanged()
    }

    fun resetData() {
        users.clear()
    }

}
